package cn.zhentao.service;

import cn.zhentao.entity.AiSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AI会话管理服务 - 管理所有AI功能的会话状态和记忆
 */
@Slf4j
@Service
public class AiSessionService {
    
    /**
     * AI会话缓存 - 实际项目中可以使用Redis
     */
    private final Map<String, AiSession> sessionCache = new ConcurrentHashMap<>();
    
    /**
     * 会话超时时间（分钟）
     */
    private static final int SESSION_TIMEOUT_MINUTES = 60;
    
    /**
     * 创建新的AI会话
     */
    public AiSession createAiSession(Long userId, AiSession.AiFeatureType featureType) {
        String sessionId = generateSessionId(userId, featureType);
        
        // 检查是否已存在会话，如果存在则复用
        AiSession existingSession = sessionCache.get(sessionId);
        if (existingSession != null && isSessionValid(existingSession)) {
            log.info("复用现有AI会话: userId={}, featureType={}, sessionId={}", userId, featureType, sessionId);
            return existingSession;
        }
        
        AiSession session = new AiSession();
        session.setSessionId(sessionId);
        session.setUserId(userId);
        session.setFeatureType(featureType);
        session.setSessionState(AiSession.SessionState.ACTIVE);
        
        // 根据功能类型设置特定配置
        configureSessionByFeatureType(session, featureType);
        
        sessionCache.put(sessionId, session);
        log.info("创建AI会话: userId={}, featureType={}, sessionId={}", userId, featureType, sessionId);
        
        return session;
    }
    
    /**
     * 获取AI会话
     */
    public AiSession getAiSession(String sessionId) {
        AiSession session = sessionCache.get(sessionId);
        if (session != null && isSessionValid(session)) {
            return session;
        }
        return null;
    }
    
    /**
     * 获取或创建AI会话
     */
    public AiSession getOrCreateAiSession(Long userId, AiSession.AiFeatureType featureType) {
        String sessionId = generateSessionId(userId, featureType);
        AiSession session = sessionCache.get(sessionId);
        
        // 检查会话是否有效
        if (session != null && isSessionValid(session)) {
            log.debug("复用现有AI会话: sessionId={}", sessionId);
            return session;
        }
        
        // 创建新会话
        log.info("创建新AI会话: userId={}, featureType={}", userId, featureType);
        session = createAiSession(userId, featureType);
        
        return session;
    }
    
    /**
     * 更新AI会话
     */
    public void updateAiSession(AiSession session) {
        session.setUpdateTime(LocalDateTime.now());
        sessionCache.put(session.getSessionId(), session);
        log.debug("更新AI会话: sessionId={}, featureType={}", 
                 session.getSessionId(), session.getFeatureType());
    }
    
    /**
     * 添加对话记录
     */
    public void addConversationRecord(String sessionId, String userInput, String aiResponse, 
                                    Map<String, Object> metadata) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            session.addConversationRecord(userInput, aiResponse, metadata);
            updateAiSession(session);
            log.debug("添加对话记录: sessionId={}, 交互次数={}", 
                     sessionId, session.getSessionStats().getTotalInteractions());
        }
    }
    
    /**
     * 设置用户偏好
     */
    public void setUserPreference(String sessionId, String key, Object value) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            session.getUserPreferences().getCustomSettings().put(key, value);
            updateAiSession(session);
        }
    }
    
    /**
     * 设置上下文数据
     */
    public void setContextData(String sessionId, String key, Object value) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            session.setContextValue(key, value);
            updateAiSession(session);
        }
    }
    
    /**
     * 获取上下文数据
     */
    public Object getContextData(String sessionId, String key) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            return session.getContextValue(key);
        }
        return null;
    }
    
    /**
     * 暂停会话
     */
    public void pauseSession(String sessionId) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            session.setSessionState(AiSession.SessionState.PAUSED);
            updateAiSession(session);
        }
    }
    
    /**
     * 恢复会话
     */
    public void resumeSession(String sessionId) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            session.setSessionState(AiSession.SessionState.ACTIVE);
            updateAiSession(session);
        }
    }
    
    /**
     * 结束会话
     */
    public void endSession(String sessionId) {
        AiSession session = getAiSession(sessionId);
        if (session != null) {
            session.setSessionState(AiSession.SessionState.ENDED);
            updateAiSession(session);
            log.info("结束AI会话: sessionId={}, 总交互次数={}", 
                    sessionId, session.getSessionStats().getTotalInteractions());
        }
    }
    
    /**
     * 删除会话
     */
    public void removeSession(String sessionId) {
        sessionCache.remove(sessionId);
        log.info("删除AI会话: sessionId={}", sessionId);
    }
    
    /**
     * 清理过期会话
     */
    public void cleanExpiredSessions() {
        LocalDateTime expireTime = LocalDateTime.now().minusMinutes(SESSION_TIMEOUT_MINUTES);
        sessionCache.entrySet().removeIf(entry -> {
            AiSession session = entry.getValue();
            boolean expired = session.getUpdateTime().isBefore(expireTime);
            if (expired) {
                log.info("清理过期AI会话: sessionId={}, featureType={}", 
                        entry.getKey(), session.getFeatureType());
            }
            return expired;
        });
    }
    
    /**
     * 生成会话ID - 使用固定格式确保同一用户同一功能的会话ID一致
     */
    private String generateSessionId(Long userId, AiSession.AiFeatureType featureType) {
        return String.format("ai_%s_%s", featureType.name().toLowerCase(), userId);
    }
    
    /**
     * 检查会话是否有效
     */
    private boolean isSessionValid(AiSession session) {
        LocalDateTime expireTime = LocalDateTime.now().minusMinutes(SESSION_TIMEOUT_MINUTES);
        return session.getUpdateTime().isAfter(expireTime) && 
               session.getSessionState() != AiSession.SessionState.ENDED;
    }
    
    /**
     * 根据功能类型配置会话
     */
    private void configureSessionByFeatureType(AiSession session, AiSession.AiFeatureType featureType) {
        AiSession.UserPreferences preferences = session.getUserPreferences();
        
        switch (featureType) {
            case KNOWLEDGE_QA:
                preferences.setResponseStyle("formal");
                preferences.setMaxHistoryLength(30);
                session.setContextValue("domain", "general");
                break;
                
            case INFORMATION_QUERY:
                preferences.setResponseStyle("formal");
                preferences.setMaxHistoryLength(20);
                session.setContextValue("searchScope", "comprehensive");
                break;
                
            case TEXT_GENERATION:
                preferences.setResponseStyle("creative");
                preferences.setMaxHistoryLength(40);
                session.setContextValue("generationType", "general");
                break;
                
            case LANGUAGE_TRANSLATION:
                preferences.setResponseStyle("formal");
                preferences.setMaxHistoryLength(25);
                session.setContextValue("sourceLanguage", "auto");
                session.setContextValue("targetLanguage", "zh-CN");
                break;
                
            case EMOTIONAL_COMPANION:
                preferences.setResponseStyle("friendly");
                preferences.setMaxHistoryLength(60);
                session.setContextValue("companionMode", "supportive");
                break;
                
            case SMART_RECOMMENDATION:
                preferences.setResponseStyle("casual");
                preferences.setMaxHistoryLength(35);
                session.setContextValue("recommendationType", "general");
                break;
                
            case HEALTH_MANAGEMENT:
                preferences.setResponseStyle("caring");
                preferences.setMaxHistoryLength(45);
                session.setContextValue("healthFocus", "general");
                break;
                
            case GAME_ENTERTAINMENT:
                preferences.setResponseStyle("playful");
                preferences.setMaxHistoryLength(50);
                session.setContextValue("gameType", "general");
                break;
                
            default:
                // 使用默认配置
                break;
        }
    }
}
